package org.example.skytool.es.doc;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.example.skytool.json.JackSonUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.text.html.Option;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class EsDslUtil {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class DslResult<T> {
        private Long total;
        private Map<String, T> hits;
        private List<String> suggest;
    }

    private <T> DslResult<T> parseResponse(SearchResponse response, Class<T> clazz) {
        Suggest suggest = response.getSuggest();
        if(suggest==null){
            DslResult<T> result = new DslResult<>();
            TotalHits totalHits = response.getHits().getTotalHits();
            result.setTotal(totalHits.value);
            result.setHits(new HashMap<>());
            SearchHit[] searchHits = response.getHits().getHits();
            for (SearchHit hit : searchHits) {
                String json = hit.getSourceAsString();
                String id = hit.getId();
                T docData = JackSonUtil.parse(clazz, json);
                result.getHits().put(id, docData);
            }
            return result;
        }else{
            DslResult<T> result = new DslResult<>();
            result.setSuggest(new ArrayList<>());
            CompletionSuggestion suggestion = suggest.getSuggestion("campus");
            for(CompletionSuggestion.Entry.Option option : suggestion.getOptions()){
                String text = option.getText().string();
                result.getSuggest().add(text);
            }
            return result;
        }
    }

    public <T> DslResult<T> sendQuery(SearchRequest request, Class<T> clazz) {
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return parseResponse(response, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public SearchRequest getSearchRequest(String name){
        return new SearchRequest(name);
    }

}
